﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PodcastToMP3
{
    public static class StreamExtensions
    {
        public static T Read<T>(this System.IO.Stream Stream, long Position, long Length)
        {
            byte[] buffer = new byte[Length];
            Stream.Position = Position;
            Stream.Read(buffer, 0, (int)Length);

            object output = null;
            if (typeof(T) == typeof(byte[]))
                output = buffer;
            else if (typeof(T) == typeof(int))
            {
                // If the system architecture is little-endian (that is, little end first), 
                // reverse the byte array.
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(buffer);
                output = BitConverter.ToInt32(buffer, 0);
            }
            else if (typeof(T) == typeof(string))
            {
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                output = enc.GetString(buffer);
            }

            return (T)output;
        }
    }
}
